package game.server.world.rtree;

import rtree.ElementNotFoundException;
import rtree.IllegalValueException;
import rtree.LeafElement;
import rtree.RTree;
import rtree.RTreeException;
import rtree.RTreeInsertException;
import rtree.Rect;
import game.server.world.GameObject;

public class RTreeObject {
	private long ptr;
	
	private GameObject object;

	private RTree rtree;
	private LeafElement inWorldLeaf;
	
	public RTreeObject(RTree rtree){
		this.rtree = rtree;
	}
	
	long getPtr(){
		return this.ptr;
	}
	
	void setObject(GameObject object){
		this.object = object;
		this.ptr = object.getObjectName().hashCode();
	}
	
	void addToWorld() throws RTreeInsertException, IllegalValueException{
		Rect r = asRect();
		
		inWorldLeaf = new LeafElement(r, ptr);
		rtree.insert(inWorldLeaf);
	}
	
	void deleteFromWorld() throws RTreeException, ElementNotFoundException, IllegalValueException{
		rtree.delete(inWorldLeaf);
	}
	
	boolean needUpdate(){
		return object.isPositionChanged();
	}
	
	synchronized void updatePosition() throws IllegalValueException, RTreeInsertException, RTreeException, ElementNotFoundException{
		synchronized (object){
			Rect r = asRect();
			LeafElement leaf = new LeafElement(r, ptr);
			rtree.delete(inWorldLeaf);
			rtree.insert(leaf);
			inWorldLeaf = leaf;
			object.setPositionUpdated();
		}
	}
	
	private Rect asRect() throws IllegalValueException{
		return new Rect((int)(object.getXf() - 10), (int)(object.getYf() - 10), (int) (object.getXf() + 10), (int) (object.getYf() + 10));
	}
	
	public GameObject getObject() {
		return object;
	}
	public LeafElement getInWorldLeaf() {
		return inWorldLeaf;
	}
}
